_CART = {
  itemsInCart : 0,
  updateNavCount : function ()
  {
    $("#nav-cart-items-count").html(_CART.itemsInCart)
  },
  /**
   * change the button display for the items in cart
  **/
  itemInCart : function (id, inCart)
  {
     $('.add-to-cart-'+id).removeClass('btn-info');
     $('.add-to-cart-'+id).removeClass('btn-danger');

	 if (inCart)
	 {
       $('.add-to-cart-'+id).html('Remove');
       $('.add-to-cart-'+id).addClass('btn-danger');
	 }
	 else
	 {
       $('.add-to-cart-'+id).html('Add To Cart <i class="icon-white icon-shopping-cart">');
       $('.add-to-cart-'+id).addClass('btn-info');
	 }
  },
  /**
   * get ajax response and update items 
  **/
  ajaxResponse : function (data)
  {
	_CART.itemsInCart = 0;
    for (id in data)
	{
	  _CART.itemsInCart++;
  	  _CART.itemInCart(id, true);
	}
	_CART.updateNavCount(); 
  },

  /**
   * add item to the cart 
  **/
  addItem : function (id)
  {
	 $.ajax({
		type: "POST",
	    url: "/cart/add",
		dataType : 'json',
		data: { 'id' : id },
		success : function (data) {
		  _CART.ajaxResponse(data);
		}
	})
  },
  delItem : function (id)
  {
	 $.ajax({
		type: "POST",
	    url: "/cart/del",
		dataType : 'json',
		data: { 'id' : id },
		success : function (data) {
		  _CART.ajaxResponse(data);
		}
	})
  },
  add_remove_toggle : function (id)
  {
     if ($('.add-to-cart-'+id).html() == 'Remove')
	 {
	   _CART.itemInCart(id, false)
	   _CART.itemsInCart--;
	   _CART.updateNavCount(); 
	   _CART.delItem(id); 
	 }
	 else
	 {
	   _CART.itemInCart(id, true)
	   _CART.itemsInCart++;
	   _CART.updateNavCount(); 
	   _CART.addItem(id); 
	 }

  },
  /**
   * get current cart items from the server
  **/
  refresh : function ()
  {
	 $.ajax({
		type: "POST",
	    url: "/cart/refresh",
		dataType : 'json',
		success : function (data) {
		  _CART.ajaxResponse(data);
		}
	})
  }
}

$(function () {
  $(".add-to-cart").click( function () {
    _CART.add_remove_toggle( $(this).attr('vID') );
  });
  
  _CART.refresh( );
})
